package com.threeox.commonlibrary.ui.view.tableview;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.threeox.commonlibrary.R;
import com.threeox.commonlibrary.entity.engine.model.table.TableModelMessage;
import com.threeox.commonlibrary.ui.view.CustomHorizontalScrollView;
import com.threeox.commonlibrary.ui.view.inter.table.ITableView;
import com.threeox.commonlibrary.ui.view.inter.table.OnTableViewListener;
import com.threeox.commonlibrary.ui.view.tableview.entity.TableDataMessage;
import com.threeox.commonlibrary.util.ValueUtils;
import com.threeox.commonlibrary.util.ViewUtils;
import com.threeox.utillibrary.util.ConvertUtils;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.HandlerUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.res.LayoutUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @ClassName: CommonTableView
 *
 * @Description: Todo(自定义表格View)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2017/8/13 下午5:33
 * 
 * @version 1.0
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class CommonTableView extends LinearLayout implements ITableView, HandlerUtils.OnHandlerListener {

    private final String TAG = this.getClass().getSimpleName();

    private Context mContext;

    private ViewUtils mViewUtils;

    private TableModelMessage mTableModelMessage;
    private OnTableViewListener mOnTableViewListener;

    private int marginLeft = 25;
    private int marginRight = 25;
    private int marginTop = 25;
    private int marginBottom = 25;

    /*======================表格视图=======================*/
    /**
     * 表格左上角视图
     */
    private TextView mColumnTitleView;
    /**
     * 第一行布局（锁状态）
     */
    private LinearLayout mLockHeadLayout;
    /**
     * 第一行布局（未锁状态）
     */
    private LinearLayout mUnLockHeadLayout;
    /**
     * 第一行滚动视图（锁状态）
     */
    private CustomHorizontalScrollView mLockScrollView;
    /**
     * 第一行滚动视图（未锁状态）
     */
    private CustomHorizontalScrollView mUnLockScrollView;
    /**
     * 表格主视图
     */
    private ScrollView mTableScrollView;
    /*======================表格视图=======================*/

    private HandlerUtils mHandlerUtils;

    public CommonTableView(Context context) {
        this(context, null);
    }

    public CommonTableView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CommonTableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutUtils.inflate(getContext(), R.layout.view_table_view, this);
        this.mContext = context;
        mViewUtils = ViewUtils.newInstance();
        initView();
        setListener();
    }

    private void initView() {
        mTableScrollView = (ScrollView) findViewById(R.id.id_table_scrollView);
        mColumnTitleView = (TextView) findViewById(R.id.id_lock_head_view_Text);
        mLockHeadLayout = (LinearLayout) findViewById(R.id.id_lock_head_layout);
        mUnLockHeadLayout = (LinearLayout) findViewById(R.id.id_unlock_head_layout);
        mLockScrollView = (CustomHorizontalScrollView) findViewById(R.id.id_lock_head_view_scrollview);
        mUnLockScrollView = (CustomHorizontalScrollView) findViewById(R.id.id_unlock_head_view_scrollview);
    }

    private void setListener() {
        mHandlerUtils = HandlerUtils.getInstance().setOnHandlerListener(this);
    }

    @Override
    public void initConfig(TableModelMessage tableModelMessage) {
        this.mTableModelMessage = tableModelMessage;
    }


    @Override
    public synchronized void setValue(final List<String> headDatas, final List datas) {
        if (EmptyUtils.isNotEmpty(headDatas)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        TableDataMessage tableDataMessage = new TableDataMessage();
                        tableDataMessage.setTableOldDatas(datas);
                        tableDataMessage.addTableData(headDatas);
                        if (EmptyUtils.isNotEmpty(datas)) {
                            for (Object data : datas) {
                                List<String> tableData = new ArrayList<String>();
                                for (String headName : headDatas) {
                                    Object result = ValueUtils.getObjValue(data, headName);
                                    if (result == null) {
                                        result = mTableModelMessage.getNullableString();
                                    }
                                    tableData.add(String.valueOf(result));
                                }
                                tableDataMessage.addTableData(tableData);
                            }
                        }
                        List<List<String>> tableDatas = tableDataMessage.getTableDatas();
                        //检查数据，如果有一行数据长度不一致，以最长为标准填"N/A"字符串,如果有null也替换
                        int maxLength = 0;
                        for (int i = 0; i < tableDatas.size(); i++) {
                            if (tableDatas.get(i).size() >= maxLength) {
                                maxLength = tableDatas.get(i).size();
                            }
                            List<String> rowDatas = tableDatas.get(i);
                            for (int j = 0; j < rowDatas.size(); j++) {
                                if (rowDatas.get(j) == null || rowDatas.get(j).equals("")) {
                                    rowDatas.set(j, mTableModelMessage.getNullableString());
                                }
                            }
                            tableDatas.set(i, rowDatas);
                        }
                        for (int i = 0; i < tableDatas.size(); i++) {
                            List<String> rowDatas = tableDatas.get(i);
                            if (rowDatas.size() < maxLength) {
                                int size = maxLength - rowDatas.size();
                                for (int j = 0; j < size; j++) {
                                    rowDatas.add(mTableModelMessage.getNullableString());
                                }
                                tableDatas.set(i, rowDatas);
                            }
                        }
                        measureColumnWidth(tableDataMessage);
                        measureRowHeight(tableDataMessage);
                        if (mTableModelMessage.isLockHeadRow()) {
                            List<String> fristRowDatas = tableDatas.get(0);
                            if (mTableModelMessage.isLockFristColumn()) {
                                //锁定第一列
                                tableDataMessage.setColumnTitle(fristRowDatas.get(0));
                                fristRowDatas.remove(0);
                                tableDataMessage.setTableHeadDatas(fristRowDatas);
                                //构造第一列数据,并且构造表格每行数据
                                for (int i = 1; i < tableDatas.size(); i++) {
                                    List<String> rowDatas = tableDatas.get(i);
                                    tableDataMessage.addTableColumnData(rowDatas.get(0));
                                    rowDatas.remove(0);
                                    tableDataMessage.addTableRowData(rowDatas);
                                }
                            } else {
                                tableDataMessage.setTableHeadDatas(fristRowDatas);
                                for (int i = 1; i < tableDatas.size(); i++) {
                                    tableDataMessage.addTableRowData(tableDatas.get(i));
                                }
                            }
                        } else {
                            if (mTableModelMessage.isLockFristColumn()) {
                                //锁定第一列
                                //构造第一列数据,并且构造表格每行数据
                                for (int i = 0; i < tableDatas.size(); i++) {
                                    List<String> rowDatas = tableDatas.get(i);
                                    tableDataMessage.addTableColumnData(rowDatas.get(0));
                                    rowDatas.remove(0);
                                    tableDataMessage.addTableRowData(rowDatas);
                                }
                            } else {
                                for (int i = 0; i < tableDatas.size(); i++) {
                                    tableDataMessage.addTableRowData(tableDatas.get(i));
                                }
                            }
                        }
                        mHandlerUtils.put(tableDataMessage).send();
                    } catch (Exception e) {
                        if (mOnTableViewListener != null) {
                            mOnTableViewListener.onTableShowFeated(e.getMessage());
                        }
                    }
                }
            }).start();
        } else {
            LogUtils.d(TAG, "设置表格数据标题不能为空!");
        }
    }

    @Override
    public void setOnTableViewListener(OnTableViewListener onTableViewListener) {
        this.mOnTableViewListener = onTableViewListener;
    }

    @Override
    public void onHandleMessage(Message msg) throws Exception {
        try {
            TableDataMessage dataMessage = (TableDataMessage) msg.obj;
            mTableScrollView.removeAllViews();
            mLockScrollView.removeAllViews();
            mUnLockScrollView.removeAllViews();
            if (mTableModelMessage.isLockHeadRow()) {
                if (mTableModelMessage.isLockFristColumn()) {
                    mLockHeadLayout.setVisibility(VISIBLE);
                    mUnLockHeadLayout.setVisibility(GONE);
                } else {
                    mLockHeadLayout.setVisibility(GONE);
                    mUnLockHeadLayout.setVisibility(VISIBLE);
                }
                creatHeadView(dataMessage);
            } else {
                mLockHeadLayout.setVisibility(GONE);
                mUnLockHeadLayout.setVisibility(GONE);
            }
            createTableView(dataMessage);
            if (mOnTableViewListener != null) {
                mOnTableViewListener.onTableShowSuccess();
            }
        } catch (Exception e) {
            if (mOnTableViewListener != null) {
                mOnTableViewListener.onTableShowFeated(e.getMessage());
            }
        }
    }

    /**
     * 创建头部视图
     */
    private void creatHeadView(final TableDataMessage tableDataMessage) {
        if (mTableModelMessage.isLockFristColumn()) {
            mColumnTitleView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableHeadTextColor()));
            mColumnTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
            mColumnTitleView.setText(tableDataMessage.getColumnTitle());
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mColumnTitleView.getLayoutParams();
            layoutParams.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(0));
            layoutParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(0));
            layoutParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
            mColumnTitleView.setLayoutParams(layoutParams);
            //构造滚动视图
            createScollview(mLockScrollView, tableDataMessage.getTableHeadDatas(), true, tableDataMessage);
            tableDataMessage.addScrollView(mLockScrollView);
            mLockScrollView.scrollTo(0, 0);
            mLockScrollView.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
                @Override
                public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                    changeAllScrollView(x, y, tableDataMessage.getScrollViews());
                }
            });
        } else {
            createScollview(mUnLockScrollView, tableDataMessage.getTableHeadDatas(), true, tableDataMessage);
            tableDataMessage.addScrollView(mUnLockScrollView);
            mUnLockScrollView.scrollTo(0, 0);
            mUnLockScrollView.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
                @Override
                public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                    changeAllScrollView(x, y, tableDataMessage.getScrollViews());
                }
            });
        }
    }

    /**
     * 构造滚动视图
     *
     * @param scrollView
     * @param datas
     * @param isFristRow 是否是第一行
     */
    private void createScollview(HorizontalScrollView scrollView, List<String> datas, boolean isFristRow, TableDataMessage tableDataMessage) {
        //设置LinearLayout
        LinearLayout linearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        for (int i = 0; i < datas.size(); i++) {
            //构造单元格
            TextView textView = new TextView(mContext);
            if (isFristRow) {
                textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableHeadTextColor()));
            } else {
                textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
            }
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
            textView.setGravity(Gravity.CENTER);
            textView.setText(datas.get(i));
            //设置布局
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
            textView.setLayoutParams(textViewParams);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            ViewGroup.LayoutParams textViewParamsCopy = textView.getLayoutParams();
            if (mTableModelMessage.isLockFristColumn()) {
                textViewParamsCopy.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(i + 1));
            } else {
                textViewParamsCopy.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(i));
            }
            linearLayout.addView(textView);
            //画分隔线
            if (i != datas.size() - 1) {
                View splitView = new View(mContext);
                ViewGroup.LayoutParams splitViewParmas = new ViewGroup.LayoutParams(ConvertUtils.dp2px(mContext, 1),
                        ViewGroup.LayoutParams.MATCH_PARENT);
                splitView.setLayoutParams(splitViewParmas);
                if (isFristRow) {
                    splitView.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.white));
                } else {
                    splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                }
                linearLayout.addView(splitView);
            }
        }
        scrollView.addView(linearLayout);
    }

    /**
     * 构造表格主视图
     */
    private void createTableView(TableDataMessage dataMessage) {
        if (mTableModelMessage.isLockFristColumn()) {
            createLockColumnView(dataMessage);
        } else {
            createUnLockColumnView(dataMessage);
        }
    }

    /**
     * 创建锁定列视图
     */
    private void createLockColumnView(final TableDataMessage tableDataMessage) {
        View lockTableViewContent = LayoutInflater.from(mContext).inflate(R.layout.view_lock_table_contentview, null);
        LinearLayout lockViewParent = (LinearLayout) lockTableViewContent.findViewById(R.id.lockView_parent);
        CustomHorizontalScrollView lockScrollViewParent = (CustomHorizontalScrollView) lockTableViewContent.findViewById(R.id.lockScrollView_parent);
        for (int i = 0; i < tableDataMessage.getTableColumnDatas().size(); i++) {
            //构造TextView容器，如果要设置背景色设置这一个而不是设置TextView，TextView有外边距设置不全
            LinearLayout textViewContainer = new LinearLayout(mContext);
            LinearLayout.LayoutParams textLinearParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            textViewContainer.setOrientation(LinearLayout.HORIZONTAL);
            textViewContainer.setLayoutParams(textLinearParams);
            //构造TextView
            TextView textView = new TextView(mContext);
            //设置布局
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
            textView.setLayoutParams(textViewParams);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
            textView.setText(tableDataMessage.getTableColumnDatas().get(i));
            textView.setGravity(Gravity.CENTER);
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(0));
            if (mTableModelMessage.isLockHeadRow()) {
                layoutParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i + 1));
            } else {
                layoutParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i));
            }
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setLayoutParams(layoutParams);
            if (!mTableModelMessage.isLockHeadRow()) {
                if (i == 0) {
                    textViewContainer.setBackgroundColor(ContextCompat.getColor(mContext, mTableModelMessage.getFristRowBackGroudColor()));
                    textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableHeadTextColor()));
                } else {
                    textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
                }
            } else {
                textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
            }
            textViewContainer.addView(textView);
            //表格线
            View splite = new View(mContext);
            ViewGroup.LayoutParams spliteLayoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ConvertUtils.dp2px(mContext, 1));
            splite.setLayoutParams(spliteLayoutParam);
            splite.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
            lockViewParent.addView(textViewContainer);
            lockViewParent.addView(splite);
        }
        //构造滚动视图
        LinearLayout scollViewItemContentView = new LinearLayout(mContext);
        LinearLayout.LayoutParams scollViewItemContentViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        scollViewItemContentView.setLayoutParams(scollViewItemContentViewParams);
        scollViewItemContentView.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < tableDataMessage.getTableRowDatas().size(); i++) {
            final int position = i;
            final List<String> datas = tableDataMessage.getTableRowDatas().get(i);
            //设置LinearLayout
            LinearLayout linearLayout = new LinearLayout(mContext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.setBackgroundResource(R.drawable.table_row_bg);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setClickable(true);
            if (!mTableModelMessage.isLockHeadRow()) {
                if (i == 0) {
                    linearLayout.setBackgroundColor(ContextCompat.getColor(mContext, mTableModelMessage.getFristRowBackGroudColor()));
                }
            }
            for (int j = 0; j < datas.size(); j++) {
                //构造单元格
                TextView textView = new TextView(mContext);
                if (!mTableModelMessage.isLockHeadRow()) {
                    if (i == 0) {
                        textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableHeadTextColor()));
                    } else {
                        textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
                    }
                } else {
                    textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
                }
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
                textView.setGravity(Gravity.CENTER);
                textView.setText(datas.get(j));
                //设置布局
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
                if (mTableModelMessage.isLockHeadRow()) {
                    textViewParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i + 1));
                } else {
                    textViewParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i));
                }
                textView.setLayoutParams(textViewParams);
                ViewGroup.LayoutParams textViewParamsCopy = textView.getLayoutParams();
                if (datas.size() == tableDataMessage.getColumnMaxWidths().size()) {
                    textViewParamsCopy.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(j));
                } else {
                    textViewParamsCopy.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(j + 1));
                }
                textView.setSingleLine();
                textView.setEllipsize(TextUtils.TruncateAt.END);
                linearLayout.addView(textView);
                //右侧分隔线
                if (j != datas.size() - 1) {
                    View splitView = new View(mContext);
                    ViewGroup.LayoutParams splitViewParmas = new ViewGroup.LayoutParams(ConvertUtils.dp2px(mContext, 1),
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    splitView.setLayoutParams(splitViewParmas);
                    if (!mTableModelMessage.isLockHeadRow()) {
                        if (i == 0) {
                            splitView.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.white));
                        } else {
                            splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                        }
                    } else {
                        splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                    }
                    linearLayout.addView(splitView);
                }
            }
            scollViewItemContentView.addView(linearLayout);
            //底部分隔线
            View splite = new View(mContext);
            ViewGroup.LayoutParams spliteLayoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ConvertUtils.dp2px(mContext, 1));
            splite.setLayoutParams(spliteLayoutParam);
            splite.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
            scollViewItemContentView.addView(splite);

            linearLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnTableViewListener != null) {
                        Object data = tableDataMessage.getTableOldDatas().get(position);
                        mOnTableViewListener.OnTableRowClick(position, data);
                    }
                }
            });
            linearLayout.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (mOnTableViewListener != null) {
                        Object data = tableDataMessage.getTableOldDatas().get(position);
                        Boolean result = mOnTableViewListener.OnTableRowLongClick(position, data);
                        if (null != result) {
                            return result;
                        }
                    }
                    return false;
                }
            });
        }
        lockScrollViewParent.addView(scollViewItemContentView);
        tableDataMessage.addScrollView(lockScrollViewParent);
        lockScrollViewParent.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
            @Override
            public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                changeAllScrollView(x, y, tableDataMessage.getScrollViews());
            }
        });
        mTableScrollView.addView(lockTableViewContent);
    }

    /**
     * 创建不锁定列视图
     */
    private void createUnLockColumnView(final TableDataMessage tableDataMessage) {
        View lockTableViewContent = LayoutInflater.from(mContext).inflate(R.layout.view_unlock_table_contentview, null);
        CustomHorizontalScrollView lockScrollViewParent = (CustomHorizontalScrollView) lockTableViewContent.findViewById(R.id.unlockScrollView_parent);
        //构造滚动视图
        LinearLayout scollViewItemContentView = new LinearLayout(mContext);
        LinearLayout.LayoutParams scollViewItemContentViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        scollViewItemContentView.setLayoutParams(scollViewItemContentViewParams);
        scollViewItemContentView.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < tableDataMessage.getTableRowDatas().size(); i++) {
            final int position = i;
            final List<String> datas = tableDataMessage.getTableRowDatas().get(i);
            //设置LinearLayout
            LinearLayout linearLayout = new LinearLayout(mContext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.setBackgroundResource(R.drawable.table_row_bg);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setClickable(true);
            if (!mTableModelMessage.isLockHeadRow()) {
                if (i == 0) {
                    linearLayout.setBackgroundColor(ContextCompat.getColor(mContext, mTableModelMessage.getFristRowBackGroudColor()));
                }
            }
            for (int j = 0; j < datas.size(); j++) {
                //构造单元格
                TextView textView = new TextView(mContext);
                if (!mTableModelMessage.isLockHeadRow()) {
                    if (i == 0) {
                        textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableHeadTextColor()));
                    } else {
                        textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
                    }
                } else {
                    textView.setTextColor(ContextCompat.getColor(mContext, mTableModelMessage.getTableContentTextColor()));
                }
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
                textView.setGravity(Gravity.CENTER);
                textView.setText(datas.get(j));
                //设置布局
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
                if (mTableModelMessage.isLockHeadRow()) {
                    textViewParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i + 1));
                } else {
                    textViewParams.height = ConvertUtils.dp2px(mContext, tableDataMessage.getRowMaxHeights().get(i));
                }
                textView.setLayoutParams(textViewParams);
                ViewGroup.LayoutParams textViewParamsCopy = textView.getLayoutParams();
                textViewParamsCopy.width = ConvertUtils.dp2px(mContext, tableDataMessage.getColumnMaxWidths().get(j));
                textView.setSingleLine();
                textView.setEllipsize(TextUtils.TruncateAt.END);
                linearLayout.addView(textView);
                //右侧分隔线
                if (j != datas.size() - 1) {
                    View splitView = new View(mContext);
                    ViewGroup.LayoutParams splitViewParmas = new ViewGroup.LayoutParams(ConvertUtils.dp2px(mContext, 1),
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    splitView.setLayoutParams(splitViewParmas);
                    if (!mTableModelMessage.isLockHeadRow()) {
                        if (i == 0) {
                            splitView.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.white));
                        } else {
                            splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                        }
                    } else {
                        splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                    }
                    linearLayout.addView(splitView);
                }
            }
            scollViewItemContentView.addView(linearLayout);
            //底部分隔线
            View splite = new View(mContext);
            ViewGroup.LayoutParams spliteLayoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ConvertUtils.dp2px(mContext, 1));
            splite.setLayoutParams(spliteLayoutParam);
            splite.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
            scollViewItemContentView.addView(splite);

            linearLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnTableViewListener != null) {
                        Object data = tableDataMessage.getTableOldDatas().get(position);
                        mOnTableViewListener.OnTableRowClick(position, data);
                    }
                }
            });
            linearLayout.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (mOnTableViewListener != null) {
                        Object data = tableDataMessage.getTableOldDatas().get(position);
                        Boolean result = mOnTableViewListener.OnTableRowLongClick(position, data);
                        if (null != result) {
                            return result;
                        }
                    }
                    return false;
                }
            });
        }
        lockScrollViewParent.addView(scollViewItemContentView);
        tableDataMessage.addScrollView(lockScrollViewParent);
        lockScrollViewParent.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
            @Override
            public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                changeAllScrollView(x, y, tableDataMessage.getScrollViews());
            }
        });
        mTableScrollView.addView(lockTableViewContent);
    }

    /**
     * 改变所有滚动视图位置
     *
     * @param x
     * @param y
     */
    private void changeAllScrollView(int x, int y, List<HorizontalScrollView> scrollViews) {
        if (scrollViews.size() > 0) {
            /*if (mTableViewListener!=null){
                mTableViewListener.onTableViewScrollChange(x,y);
            }*/
            for (int i = 0; i < scrollViews.size(); i++) {
                HorizontalScrollView scrollView = scrollViews.get(i);
                scrollView.scrollTo(x, y);
            }
        }
    }

    /**
     * 计算列的最大宽度
     */
    private void measureColumnWidth(TableDataMessage dataMessage) {
        //初始化每列最大宽度
        for (int i = 0; i < dataMessage.getTableDatas().size(); i++) {
            List<String> rowDatas = dataMessage.getTableDatas().get(i);
            // StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < rowDatas.size(); j++) {
                TextView textView = new TextView(mContext);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
                textView.setText(rowDatas.get(j));
                textView.setGravity(Gravity.CENTER);
                //设置布局
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);//android:layout_margin="15dp"
                textView.setLayoutParams(textViewParams);
                if (i == 0) {
                    dataMessage.getColumnMaxWidths().add(measureTextWidth(textView, rowDatas.get(j)));
                    // buffer.append("[" + measureTextWidth(textView, rowDatas.get(j)) + "]");
                } else {
                    int length = dataMessage.getColumnMaxWidths().get(j);
                    int current = measureTextWidth(textView, rowDatas.get(j));
                    if (current > length) {
                        dataMessage.getColumnMaxWidths().set(j, current);
                    }
                    // buffer.append("[" + measureTextWidth(textView, rowDatas.get(j)) + "]");
                }
            }
        }
    }

    /**
     * 初始化每行最大高度
     */
    private void measureRowHeight(TableDataMessage dataMessage) {
        //初始化每行最大高度
        for (int i = 0; i < dataMessage.getTableDatas().size(); i++) {
            List<String> rowDatas = dataMessage.getTableDatas().get(i);
            // StringBuffer buffer = new StringBuffer();
            TextView textView = new TextView(mContext);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTableModelMessage.getTextViewSize());
            textView.setGravity(Gravity.CENTER);
            //设置布局
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            textViewParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);//android:layout_margin="15dp"
            textView.setLayoutParams(textViewParams);
            int maxHeight = measureTextHeight(textView, rowDatas.get(0));
            dataMessage.getRowMaxHeights().add(maxHeight);
            for (int j = 0; j < rowDatas.size(); j++) {
                int currentHeight = measureTextHeight(textView, rowDatas.get(j));
                // buffer.append("[" + currentHeight + "]");
                if (currentHeight > maxHeight) {
                    dataMessage.getRowMaxHeights().set(i, currentHeight);
                }
            }
        }
    }

    /**
     * 根据最大最小值，计算TextView的宽度
     *
     * @param textView
     * @param text
     * @return
     */
    private int measureTextWidth(TextView textView, String text) {
        if (textView != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
            int width = ConvertUtils.px2dp(mContext, layoutParams.leftMargin) +
                    ConvertUtils.px2dp(mContext, layoutParams.rightMargin) +
                    getTextViewWidth(textView, text) + 40;
            if (width <= mTableModelMessage.getMinColumnWidth()) {
                return mTableModelMessage.getMinColumnWidth();
            } else if (width > mTableModelMessage.getMinColumnWidth() && width <= mTableModelMessage.getMaxColumnWidth()) {
                return width;
            } else {
                return mTableModelMessage.getMaxColumnWidth();
            }
        }
        return 0;
    }

    /**
     * 根据文字计算textview的高度
     *
     * @param textView
     * @param text
     * @return
     */
    private int getTextViewHeight(TextView textView, String text) {
        if (textView != null) {
            int width = measureTextWidth(textView, text);
            TextPaint textPaint = textView.getPaint();
            StaticLayout staticLayout = new StaticLayout(text, textPaint, ConvertUtils.dp2px(mContext, width), Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            int height = ConvertUtils.px2dp(mContext, staticLayout.getHeight());
            return height;
        }
        return 0;
    }

    /**
     * 根据文字计算textview的高度
     *
     * @param view
     * @param text
     * @return
     */
    private int getTextViewWidth(TextView view, String text) {
        if (view != null) {
            TextPaint paint = view.getPaint();
            return ConvertUtils.px2dp(mContext, (int) paint.measureText(text));
        }
        return 0;
    }

    /**
     * 计算TextView高度
     *
     * @param textView
     * @param text
     * @return
     */
    private int measureTextHeight(TextView textView, String text) {
        if (textView != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
            int height = getTextViewHeight(textView, text);
            if (height < mTableModelMessage.getMinRowHeight()) {
                return mTableModelMessage.getMinRowHeight();
            } else if (height > mTableModelMessage.getMinRowHeight() && height < mTableModelMessage.getMaxRowHeight()) {
                return height;
            } else {
                return mTableModelMessage.getMaxRowHeight();
            }
        }
        return 0;
    }

    @Override
    public void release() {

    }
}
